<?php

namespace app\business\controller;

use app\models\{Business};
use think\Validate;
use think\Db;

class Index extends Base
{
    public function login()
    {
        $business_id = session('business_id');
        if (Business::get($business_id)) {
            return redirect('/main/index');
        }
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require'
            ], [
                'username.require' => '账号不能为空',
                'password.require' => '密码不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $code = captcha_check($data['code']);
            if (!$code) {
                return json(['status' => 1, 'msg' => '请输入正确验证码']);
            }
            $business = Business::get(['account' => $data['username']]);
            if (empty($business)) {
                return json(['status' => 1, 'msg' => '账号或密码错误']);
            }
            if ($business['password'] != md5(md5($data['password']))) {
                return json(['status' => 1, 'msg' => '密码错误']);
            }
            if ($business['status'] == 3) {
                return json(['status' => 1, 'msg' => '账号已禁用']);
            }
            session('business_id', $business['id']);
            return json(['status' => 0, 'msg' => '登陆成功', 'url' => url('/main/index')]);
        }
        return view(null, [
            'data' => []
        ]);
    }

    public function logout()
    {
        session('business_id', null);
        $this->redirect('index/login');
    }
}
